import model from './model'
import * as echarts from 'echarts'

export default {
  data() {
    return {
      model: model(),
      // 图表id
      chartsId: null,
    }
  },
  props: {
    /**
     * id
     */
    id: {
      type: String,
      default: '',
    },
    /**
     * width
     */
    width: {
      type: String,
      default: '100px',
    },
    /**
     * height
     */
    height: {
      type: String,
      default: '100px',
    },
    /**
     * 图表数据
     */
    dataList: {
      type: Array,
      default: () => [],
    },
    /**
     * 图表X轴数据
     */
    axisList: {
      type: Array,
      default: [],
    },
    /**
     * 主题
     */
    theme: {
      type: String,
      default: 'deep-grey',
    },
  },
  watch: {
    /**
     * 监听数据更新图表
     */
    dataList() {
      this.getCharts()
    },
    /**
     * 监听数据更新图表
     */
    theme() {
      this.getCharts()
    },
  },
  methods: {
    getCharts() {
      // 基于准备好的dom，初始化echarts实例
      const colorList = ['#5470c6', '#91cc75', '#fac858', '#ee6666', '#cca856', '#fd6d26']
      let myChart = null
      if (myChart !== null && myChart !== '' && myChart !== undefined) {
        myChart.dispose()
      } else {
        myChart = echarts.init(document.getElementById(this.id))
      }
      /*
       * 绘制图表
       */
      const option = {
        color: colorList,
        // ---- gird区域 ---
        grid: {
          top: '5%',
          left: '5%',
          right: '5%',
          bottom: '5%',
          containLabel: true,
        },
        tooltip: {
          trigger: 'axis',
          confine: true,
        },
        legend: {
          top: '-5%',
          right: '0%',
          itemWidth: 10,
          itemHeight: 10,
          textStyle: { color: '#fff' },
        },
        textStyle: {
          color: { default: '#CCCCCC', violet: '#CCCCCC', 'deep-blue': '#fff' }[this.theme],
        },
        xAxis: [
          {
            axisTick: {
              show: false,
            },
            axisLabel: {
              color: '#fff',
              interval: 0,
              rotate: 0,
              margin: 14,
              align: 'center',
              verticalAlign: 'top',
            },
            type: 'category',
            data: this.axisList,
            axisPointer: {
              type: 'shadow',
            },
          },
        ],
        yAxis: [
          {
            type: 'value',
            name: '',
            min: 0,
            interval: 'auto',
            axisLabel: {
              formatter: '{value}',
            },
            splitLine: {
              lineStyle: {
                color: 'rgba(255,255,255,0.12)',
              },
            },
          },
        ],
        series: this.dataList,
      }
      myChart.setOption(option)
    },
  },
  mounted() {
    this.$nextTick(() => {
      this.getCharts()
    })
  },
}
